package cn.itsource.ymcc.service.impl;

import cn.itsource.ymcc.constant.Constants;
import cn.itsource.ymcc.domain.Login;
import cn.itsource.ymcc.domain.User;
import cn.itsource.ymcc.dto.UserRegisterDto;
import cn.itsource.ymcc.feignclient.UaaFeignClient;
import cn.itsource.ymcc.mapper.UserMapper;
import cn.itsource.ymcc.result.JsonResult;
import cn.itsource.ymcc.service.IUserService;
import cn.itsource.ymcc.util.AssertUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 会员登录账号 服务实现类
 * </p>
 *
 * @author cff
 * @since 2024-06-10
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private UaaFeignClient uaaFeignClient;
    @Override
//    @Transactional //在一个业务里面有多次对数据库写的操作就要加上事务
    @GlobalTransactional
    public JsonResult register(UserRegisterDto registerDto) {

        String phoneKey = Constants.SMS_REGISTER + registerDto.getPhone();
        //验证短信验证码
        AssertUtil.isTrue(redisTemplate.hasKey(phoneKey),"手机验证码已过期");
        String phoneCode = redisTemplate.opsForValue().get(phoneKey).toString();
        AssertUtil.isTrue(phoneCode.equalsIgnoreCase(registerDto.getSmsCode()),"手机验证码输入错误");
        //用户注册
        User user = User.of(registerDto);
        super.save(user);
        //继续保存 login  使用openfeign 远程调用
        JsonResult jsonResult = uaaFeignClient.saveOrUpdate(getLogin(registerDto));
        String data = jsonResult.getData().toString();
        //我在使用openfeign进行数据调用的会出现  Long转Integer
        user.setLoginId(Long.valueOf(data));//设置loginId
        //int i = 1/0;
        super.updateById(user);
        return JsonResult.success();
    }

    /**
     * 构建login
     * @param registerDto
     * @return
     */
    private static Login getLogin(UserRegisterDto registerDto) {
        Login login = new Login();
        login.setUsername(registerDto.getPhone());
        login.setPassword(new BCryptPasswordEncoder().encode(registerDto.getPassword()));
        login.setType(registerDto.getRegChannel());
        login.setEnabled(true);
        return login;
    }

}
